var Web3 = require('web3');
var fs = require('fs');

let web3 = new Web3()
web3.setProvider("HTTP://127.0.0.1:8545")
 
// 获取json文件中的 abi  bytecode
var teamjson;
let abi;
let bytecode;
fs.readFile('../build/contracts/MetaCoin.json', 'utf-8', (err, data)=>{
    if(err) throw err;
    teamjson = JSON.parse(data);
    abi = teamjson.abi;
    bytecode = teamjson.bytecode;
});


// let instance = web3.eth.Contract(abi,"0x9317CEE02448139Bd7d1614d6371e99f6e84E177")
// module.exports = instance

// // 合约的abi
// // let abi = [{"constant":false,"inputs":[{"name":"message","type":"string"}],"name":"setMessage","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getMessage","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"str","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]
// //合约地址
// let contractInstance;
var conn = async()=>{
    try{
        var accounts = await web3.eth.getAccounts(); // 获取账户
        let address = accounts[0]   //'0x7f61E1A3970777C3C25DA410fD6E2c3CfCFB953a';
        //此处abi 已经是json对象了不需要进行parse动作    
        // console.info(abi);

        contractInstance = await new web3.eth.Contract(abi, address);


        const from = accounts[0];
        const to = accounts[2];
        // let v1 = await contractInstance.methods.getMessage();
        // console.log('v1:', v1)
        let res = await contractInstance.methods.sendCoin(to, 500).send({
            from: from,
            value: 0
        });
        console.log('res:', res)
        // let v2 = await contractInstance.methods.getBalance(from);
        // console.log('v2:', v2)

    }
    catch(error){
        console.log("team 合约部署失败");
        console.error(error);
    }
};
// //console.log('address',contractInstance.options.address);
conn(); // 测试
// module.exports = contractInstance;